'use strict';

const uidObj = require('uni-id');
const uidPay = require('uni-pay');
const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;

module.exports = class VIPController extends Controller {

	// 数据
	async data() {
		let response = {
			code: 1,
		};

		const start = new Date().getTime();
		const {
			code,
			pay_way,
			pay_original,
			pay_trade_type,
		} = this.ctx.data;

		let uid = '';
		let shop_id
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				shop_id = userRes.userInfo.shop_id
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		if (!shop_id) {
			response.msg = '门店ID为空'
			return response;
		}

		// 获取会员数据
		const memberRes = await this.db.collection('wmzmall-member').doc(uid)
			.field({
				member_session_key: false,
				member_password: false
			}).get();

		let parameter = {};
		let member = {};
		if (memberRes && memberRes.data.length === 1) {
			member = memberRes.data[0];
		}

		if (member.is_plus !== '是') {
			/* const parameterRes = await this.db.collection('wmzmall-member-parameter').where({
				shop_id:shop_id
			}).get();
			parameter = parameterRes.data && parameterRes.data[0]; */
			const parameterRes = await this.db.collection('wmzmall-member-config').where({
				shop_id: shop_id
			}).get();
			parameter = parameterRes.data
		}

		response.datas = {
			member,
			parameter
		};

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 支付下单
	async pay() {
		let response = {
			code: 1,
		};

		const start = new Date().getTime();
		const {
			vip_id,
			code,
			pay_way,
			pay_original,
			pay_trade_type,
		} = this.ctx.data;

		let uid = '';
		let app_id
		let shop_id
		let openid
		let entitlement_id
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				app_id = userRes.userInfo.app_id
				shop_id = userRes.userInfo.shop_id
				openid = userRes.userInfo.openid
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		if (!shop_id) {
			response.msg = '门店ID为空'
			return response;
		}
		let fee = 0
		let arrival_money = 0
		let vip_name
		let paytitle
		let way
		if (vip_id) {
			let memberConfig = await this.db.collection('wmzmall-member-config').doc(vip_id).get();
			memberConfig = memberConfig.data[0]
			way = memberConfig.way
			if (way === '购买') {
				fee = memberConfig.money * 100
			} else if (way === '储值') {
				fee = memberConfig.recharge_money * 100
				arrival_money = memberConfig.arrival_money * 100
			}
			paytitle = memberConfig.name
			vip_name = memberConfig.name
		} else {
			const parameterRes = await this.db.collection('wmzmall-member-parameter').where({
				shop_id: shop_id
			}).get();
			const parameter = parameterRes.data && parameterRes.data[0];

			if (!(parameter && parameter._id)) {
				response.msg = '付费会员模式未配置';
				return response;
			}
			// 配置项
			const config = this.service.utils.getConfig();

			// 根据支付方式获取对应 code 的 openid 
			// 根据支付方式获取对应的下单数据

			fee = parameter.vip_fees * 100;
			paytitle = parameter.pay_title || (config.appabbr + '会员');
			entitlement_id = parameter.entitlement_id
		}

		const payid = 'VIP-' + new Date().getTime() + (Math.round(Math.random() * 1000000) + '').padStart(6,
			'0');
		let payres = '';
		let paypreid = '';
		let orderInfo = {};

		switch (pay_way) {
			case '微信支付':
				let wxpayOrderInfo = {};
				switch (pay_trade_type) {
					case 'APP': // APP
					case 'MWEB': // H5 微信外部浏览器
					case 'H5WX': // H5 微信公众号（内部浏览器）
					case 'NATIVE': // 二维码
					default: // 小程序微信支付
						wxpayOrderInfo = await this.service.wechat.pay(app_id, openid, payid, fee, paytitle,
							"/notify-vip/wxpay-app")
						wxpayOrderInfo = wxpayOrderInfo.data
				}
				// 下单支付参数
				orderInfo = wxpayOrderInfo;

				paypreid = wxpayOrderInfo.prepayId;
				payres = JSON.stringify(wxpayOrderInfo);
				break;
			case '支付宝':
				let alipayOrderInfo
				switch (pay_trade_type) {
					case 'APP':
						break;
					default: // 小程序支付宝支付
						alipayOrderInfo = await this.service.alipay.pay(app_id, openid, payid, fee, paytitle,
							"/notify-vip/alipay-app")
						// 下单支付参数
						orderInfo = {
							trade_no: alipayOrderInfo.data
						};
						break;
				}

				uniCloud.logger.info("alipayOrderInfo: ", alipayOrderInfo);

				paypreid = alipayOrderInfo.prepayId;
				payres = JSON.stringify(alipayOrderInfo);
				break;
			case '百度钱包':
				break;
			case 'QQ钱包':
				break;
			case '头条支付':
				break;
			case '余额支付':
				break;
			default:
				break;
		}

		let order_pay = {
			order_id: payid,
			pay_openid: openid,
			pay_way: pay_way,
			pay_original: pay_original,
			pay_trade_type: pay_trade_type,
			pay_preid: paypreid,
			pay_res: payres,
			pay_state: '待付款',
			version: 1,
			is_delete: 0,
			create_uid: uid,
			entitlement_id: entitlement_id,
			create_time: new Date().getTime(),
			vip_id: vip_id,
			vip_name:vip_name,
			arrival_money: arrival_money,
			way: way
		};
		await this.db.collection('wmzmall-order-pay').add(order_pay);

		// 返回下单数据
		orderInfo.pay_id = payid;
		response.datas = orderInfo;

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 支付状态查询
	async paystate() {
		let response = {
			code: 1,
			msg: '支付状态查询失败'
		};

		const {
			pay_id
		} = this.ctx.data;

		if (!pay_id) {
			response.msg = '交易号不存在';
			return response;
		}

		// 查询订单支付状态
		const payRes = await this.db.collection('wmzmall-member-paying').where({
			pay_id
		}).get();
		if (!payRes || payRes.data.length !== 1) {
			response.msg = '支付单不存在';
			return response;
		}

		const payObj = payRes.data[0];
		if (payObj.pay_state == '已付款') {
			response.code = 0;
			response.datas = {
				pay_state: payObj.pay_state,
				pay_id: payObj.pay_id
			};
			return response;
		}

		switch (payObj.pay_way) {
			case '微信支付':
				const uniWxpayIns = uidPay.initWeixin(uidObj.config['mp-weixin']['pay']);
				const uniWxpayRes = await uniWxpayIns.orderQuery({
					outTradeNo: pay_id,
				});

				response.code = 0;
				response.datas = {
					pay_state: payObj.pay_state,
					pay_id: payObj.pay_id,
					trade_state: uniWxpayRes.tradeState
				};
				return response;
			case '支付宝':
				const uniAlipayIns = uidPay.initWeixin(uidObj.config['mp-alipay']['pay']);
				const uniAlipayRes = await uniAlipayIns.orderQuery({
					outTradeNo: pay_id,
				});

				response.code = 0;
				response.datas = {
					pay_state: payObj.pay_state,
					pay_id: payObj.pay_id,
					trade_state: uniAlipayRes.tradeState
				};
				return response;
		}

		return response;
	}

	//积分开通
	async integral() {
		let response = {
			code: 1,
		};
		let uid = '';
		let shop_id
		const start = new Date().getTime();
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				shop_id = userRes.userInfo.shop_id
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		if (!shop_id) {
			response.msg = '门店ID为空'
			return response;
		}

		// 获取会员数据
		const memberRes = await this.db.collection('wmzmall-member').doc(uid)
			.field({
				member_session_key: false,
				member_password: false
			}).get();

		let parameter = {};
		let member = {};
		if (memberRes && memberRes.data.length === 1) {
			member = memberRes.data[0];
		}
		let member_integral_total = member.member_integral_total
		let parameterRes = await this.db.collection('wmzmall-member-config').where({
			shop_id: shop_id,
			way: '积分兑换'
		}).get();
		parameterRes = parameterRes.data[0]
		if (member.is_plus_id && member.is_plus_id === parameterRes._id) {
			response.msg = '已开通过当前会员'
			return response;
		}
		let integral = parameterRes.integral * 1
		if (member_integral_total < integral) {
			response.msg = '积分不足'
			return response;
		}

		// 修改付费会员数据
		await this.db.collection('wmzmall-member').doc(uid).update({
			member_integral_total: member.member_integral_total - integral,
			is_plus: parameterRes.name,
			is_plus_id: parameterRes._id,
			vip_price_discount: parameterRes.vip_price_discount,
			double_integral: parameterRes.double_integral,
			partner: parameterRes.partner,
			plus_time: new Date().getTime()
		});

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

}